package impl.sort;

import anaydis.sort.Sorter;
import anaydis.sort.SorterType;
import anaydis.sort.gui.ObservableSorter;
import anaydis.sort.gui.SorterListener;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: alumnosfi
 * Date: 17/01/2011
 * Time: 15:10:28
 * To change this template use File | Settings | File Templates.
 */
public abstract class AbstractSorter implements Sorter, ObservableSorter {
    private SorterType type;
    private List<SorterListener> listeners;
    protected AbstractSorter(SorterType type){
        this.type = type;
        listeners = new ArrayList();
    }
    protected <T> boolean greater(Comparator<T> c, List<T> list, int i, int j){
        for(int k=0; k<listeners.size(); k++) {
            listeners.get(k).greater(i, j);
        }
        return c.compare(list.get(i), list.get(j))>0;
    }
    protected <T> boolean equals(Comparator<T> c, List<T> list, int i, int j){
        for(int k=0; k<listeners.size(); k++) {
            listeners.get(k).equals(i, j);
        }
        return c.compare(list.get(i), list.get(j))==0;
    }
    protected <T> void swap(List<T> list, int i, int j) {
        for(int k=0; k<listeners.size(); k++){
            listeners.get(k).swap(i, j);
        }
        T t = list.get(i);
        list.set(i, list.get(j));
        list.set(j, t);
    }
    public SorterType getType() {
        return type;
    }
    public void addSorterListener(SorterListener sl) {
        listeners.add(sl);
    }
    public void removeSorterListener(SorterListener sl) {
        listeners.remove(sl);
    }
}